import router from '../router'
import bus from '@/utils/bus'
import { registerMicroApps, start, loadMicroApp } from 'qiankun'

let $micro = null
export  function onMicroLoaded(micro) {
  $micro = micro?.$micro
  bus.emit('microLoad', $micro)
  // console.log('$microbus', $micro)
}
const MICRO_CONF = [
  {
    name: 'micro-vite',
    entry:
      process.env.NODE_ENV === 'development'
        ? '//localhost:8081'
        : '/micro-vite/',
    container: '#container',
    activeRule: '/main/micro-vite',
    props: { router, path: '/main/micro-vite' }
  },
  {
    name: 'micro-webpack',
    entry:
      process.env.NODE_ENV === 'development'
        ? '//localhost:8082/index.html'
        : '/micro-webpack/',
    container: '#container',
    activeRule: '/micro-webpack',
    props: { onMicroLoaded, router, path: '/micro-webpack' }
  },
  {
    name: 'micro-vue2',
    entry:
      process.env.NODE_ENV === 'development'
        ? '//localhost:8084/index.html'
        : '/micro-vue2/',
    container: '#container',
    activeRule: '/micro-vue2',
    props: { onMicroLoaded, router, path: '/micro-vue2' }
  },
]

/* 手动加载多个子应用，不能保活 */
// let micro = null
// router.beforeEach(async (to, from, next) => {
//   const conf = MICRO_CONF.find(item => to.path.indexOf(item.activeRule) !== -1)
//   // 应用跳转
//   if (conf) {
//     micro?.unmount()
//     micro = loadMicroApp(conf)
//   }
//   next()
// })

/* 手动加载单个子应用，可以保活 */
// export function loadMicro () {
//   loadMicroApp({
//     name: 'micro-webpack',
//     entry:
//       process.env.NODE_ENV === 'development'
//         ? '//localhost:8082/index.html'
//         : '/micro-webpack/',
//     container: '#container',
//     /* 不需要配置base 会污染主应用的路由 */
//     // activeRule: '/micro-webpack',
//     props: { onMicroLoaded, router, path: '/' }
//   },
//   {
//     sandbox: {
//       prefetch: false, //取消预加载
//       strictStyleIsolation: true, // 启用shadowDOM
//       experimentalStyleIsolation: true // 增加一个特殊的选择器规则来限定其影响范围
//     }
//   })
// }
// loadMicro()

/* 自动加载多个子应用 不能保活 */
registerMicroApps(MICRO_CONF)
